// manager/pages/corporatereporting/index.js
import { request } from '../../../utils/request';
import util from '../../../common/util';
import WxValidate from '../../../common/WxValidate';
import validateIdent from '../../../common/validateIdent';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        disabled: false,
        userInfo: {},
        busiList: [],
        dict: {},
        startDate: "",
        endDate: "",
        code: "",
        form: {
            configId: "",
            pubEntName: "",              // 企业名称
            pubCreditCode: "",           // 统一社会信用代码
            pubSettlementAmount: "",     // 结汇金额
            pubContacts: "",             // 联系人
            pubPhone: "",                // 联系方式
            pubDepositType: "",          // 存款类型 ecard_busi_pub_deposit_type
            pubDepositAmount: "",        // 存款金额
            pubDepositTerm: "",          // 存款期限 ecard_busi_pub_deposit_term
            pubLoanType: "",             // 贷款类型 ecard_busi_pub_loan_type
            pubLoanAmount: "",           // 贷款金额  
            pubLoanTerm: "",             //  贷款期限 ecard_busi_pub_loan_term
            pubLoanRate: "",             // 贷款利率
            pubMarketingDate: "",   // 营销日期
            creatorId: "",
            deptId: "",
            userCode: "",
            remark: "",
        },
        // 天眼查是否开启 0：停用，1：启用
        tianyancha: '',
        //天眼查列表
        showTianyancha: false,
        tianyanchaList: [],
        currentTianyancha: null,
        searchEntName: "",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            startDate: util.getDateMonthFrist(),
            endDate: util.formatDate(new Date()),
            code: options.code,
            "form.configId": options.id,
            "form.pubMarketingDate": util.formatDate(new Date()),
        })
        wx.setNavigationBarTitle({
            title: options.name 
        })
        if(options.code == "busi_pub_International"){
            // 国际业务
            this.initValidate(["pubEntName","pubCreditCode","pubSettlementAmount","pubContacts","pubPhone","pubMarketingDate"]);
        }else if(options.code == "busi_pub_deposit"){
            // 存款
            this.initValidate(["pubEntName","pubCreditCode","pubContacts","pubPhone","pubDepositType","pubDepositAmount","pubDepositTerm","pubMarketingDate"]);
            this.getDictionaryInfo("ecard_busi_pub_deposit_type");
            this.getDictionaryInfo("ecard_busi_pub_deposit_term");
        }else if(options.code == "busi_pub_loan"){
            // 贷款
            this.initValidate(["pubEntName","pubCreditCode","pubContacts","pubPhone","pubLoanType","pubLoanAmount","pubLoanTerm","pubLoanRate","pubMarketingDate"]);
            this.getDictionaryInfo("ecard_busi_pub_loan_type");
            this.getDictionaryInfo("ecard_busi_pub_loan_term");
        }else{
            // 企业手机银行、企业智e通
            this.initValidate(["pubEntName","pubCreditCode","pubContacts","pubPhone","pubMarketingDate"]);
        }
        if(options.detailId){
            this.setData({
                disabled: true
            })
            this.getMyBusiReportDetail(options);
        }
        this.getSysConfigInfoTianyancha();
        this.getUserInfo();
        this.getReportConfigList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    // 用户信息
    getUserInfo(e) {   
        request({
            url: "/user/getUserInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                form.creatorId = res.data.userInfo.registId;
                form.deptId = res.data.userInfo.deptId;
                form.userCode = res.data.userInfo.userCode;
                this.setData({
                    userInfo: res.data.userInfo,
                    form
                }) 
            }
        }).catch(error => {
            // console.log(error)
        })     
    },
    // 获取详情
    getMyBusiReportDetail(params) {   
        request({
            url: "/busi/reportConfig/getMyBusiReportDetail",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                busiType: params.busiType,
                id: params.detailId,
                configId: params.id,
            }
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                form = Object.assign(form, res.data);
                // form.perCustIdcard = form.perCustIdcard&&util.formatCardNum(form.perCustIdcard);
                this.setData({
                    form
                }) 
            }
        }).catch(error => {
            // console.log(error)
        })     
    },
    /**
     * 获取字典
     */
    getReportConfigList() {
        request({
            url: "/busi/reportConfig/getReportConfigList",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
				dictType: "ecard_business_reporting_sort",
				busiType: 3
			}
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                this.setData({
                    busiList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })     
    },
    /**
     * 获取字典
     */
    getDictionaryInfo(dictType) {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
                dictType
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    ['dict.'+dictType]: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取天眼查是否开启
     */
    getSysConfigInfoTianyancha() {
        request({
            url: "/commonApi/getSysConfigInfo",
            method: "GET",
            data: {
                configKey: "ecard_enterprise_tianyancha"
            },
            showLoading: false
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    tianyancha: res.data.configValue
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },
    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        this.setData({
            ['form.'+key]: value
        })
    },
    /**
     * 日期选择
     */
    bindDateChange: function(e) {
        let { key } = e.currentTarget.dataset;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },
    // 企业名称键盘搜索
    entNameSearchConfirm(e){
        console.log(e.detail.value)
        this.setData({
            'form.pubEntName': e.detail.value,
            searchEntName: e.detail.value,
        })
        // 页面加载时执行一次加载
		this.searchEnterprises()
    },

    /** 查询企业 */
    searchEnterprises(){
        if(this.data.tianyancha == 1){
            if(!this.data.form.pubEntName){
                wx.showToast({
                    title: '请输入企业名称',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            this.setData({
                showTianyancha: true
            })
            if(this.data.searchEntName != this.data.form.pubEntName){
                request({
                    url: "/enterpriseMarketing/getLikeEnterpriseByTYC",
                    reqRSAENCRY: true, // 参数是否加密
                    resRSADECRY: true, // 返回值是否解密
                    data: {
                        entName: this.data.form.pubEntName
                    },
                }).then(res => {
                    if(res.code == 0){
                        console.log(res)
                        this.setData({
                            tianyanchaList: res.data,
                            searchEntName: this.data.form.pubEntName
                        })
                    }
                }).catch(error => {
                    // console.log(error)
                })
            }
        }
    },
    
    /** 关闭天眼查 */
    closeTianyancha(){
        this.setData({
            showTianyancha: false
        })
    },
    /** 选择企业 */
    tianyanchaChange(e){
        let { item } = e.currentTarget.dataset;
        this.setData({
            currentTianyancha: item
        })
    },
    /** 确认天眼查 */
    confirmTianyancha(){
        if(!this.data.currentTianyancha){
            wx.showToast({
                title: '请选择企业',
                icon: 'none',
                duration: 2000
            })
            return
        }
        let { form } = this.data;
        form.pubEntName = this.data.currentTianyancha.entName
        form.pubCreditCode = this.data.currentTianyancha.entOrgCode
        this.setData({
            form,
            searchEntName: this.data.currentTianyancha.entName,
            showTianyancha: false
        })
    },
    // 保存
    save(){
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        let { form } = this.data;
        request({
            url: "/busi/reportPublic/addReportPublicInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });                
                setTimeout(()=>{
                    wx.navigateBack()
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate(keys) {
        // 验证字段的规则
        const allRules = {
            pubEntName: {
                required: true,
            },
            pubCreditCode: {
                // required: true,
                ty: true
            },
            pubSettlementAmount: {
                required: true,
                settlementAmount: true
            },
            pubContacts: {
                required: true,
                name: true
            },
            pubPhone: {
                required: true,
                tel: true
            },
            pubDepositType: {
                required: true,
            },
            pubDepositAmount: {
                required: true,
                depositAmount: true
            },
            pubDepositTerm: {
                required: true,
            },
            pubLoanType: {
                required: true,
            },
            pubLoanAmount: {
                required: true,
                loanAmount: true
            },
            pubLoanTerm: {
                required: true,
            },
            pubLoanRate: {
                required: true,
                loanRate: true
            },
            pubMarketingDate: {
                required: true,
            },
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const allMessages = {
            pubEntName: {
                required: '请输入企业名称',
            },
            pubCreditCode: {
                // required: '请输入统一社会信用代码',
            },
            pubSettlementAmount: {
                required: '请输入结汇金额',
            },
            pubContacts: {
                required: '请输入联系人',
            },
            pubPhone: {
                required: '请输入联系方式',
                tel: '请输入正确的联系方式'
            },
            pubDepositType: {
                required: '请选择产品类型',
            },
            pubDepositAmount: {
                required: '请输入存款金额',
            },
            pubDepositTerm: {
                required: '请选择存款期限',
            },
            pubLoanType: {
                required: '请选择产品类型',
            },
            pubLoanAmount: {
                required: '请输入贷款金额',
            },
            pubLoanTerm: {
                required: '请选择贷款期限',
            },
            pubLoanRate: {
                required: '请输入贷款利率',
            },
            pubMarketingDate: {
                required: '请选择营销日期'
            },
        }

        let rules = {}; 
        let messages = {};
        keys.forEach(key => {
            rules[key] = allRules[key];
            messages[key] = allMessages[key];
        })

        this.WxValidate = new WxValidate(rules, messages)
        // 自定义验证规则
        this.WxValidate.addMethod('name', (value, param) => {
            var returnVal = true;
            if(/^[\u4e00-\u9fa5]{2,6}$/.test(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '客户名称为2-6个中文')
        // 自定义验证规则
        this.WxValidate.addMethod('ty', (value, param) => {
            if(!value){
                return true
            }
            var returnVal = true;
            if(/^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/.test(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '社会统一编码不正确')
        // 自定义验证规则
        this.WxValidate.addMethod('settlementAmount', (value, param) => {
            var returnVal = true;
            if(/^\d+(\.\d{0,2})?$/.test(value)&&value>0){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '结汇金额为大于0数字或保留2位的小数')
        // 自定义验证规则
        this.WxValidate.addMethod('depositAmount', (value, param) => {
            var returnVal = true;
            if(/^\d+(\.\d{0,2})?$/.test(value)&&value>0){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '存款金额为大于0数字或保留2位的小数')
        // 自定义验证规则
        this.WxValidate.addMethod('loanAmount', (value, param) => {
            var returnVal = true;
            if(/^\d+(\.\d{0,2})?$/.test(value)&&value>0){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '贷款金额为大于0数字或保留2位的小数')
        // 自定义验证规则
        this.WxValidate.addMethod('loanRate', (value, param) => {
            var returnVal = true;
            if(/^\d+(\.\d{0,2})?$/.test(value)&&value>0){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '贷款利率为大于0数字或保留2位的小数')
        // this.WxValidate.addMethod('amount', (value, param) => {
        //     var returnVal = true;
        //     if(/^((0{1}.\d{1,2})|([1-9]\d.{1}\d{1,2})|([1-9]+\d))$/.test(value)){
        //         returnVal = true;
        //     }else{
        //         returnVal = false;
        //         return false
        //     }
        //     return this.WxValidate.optional(value) || returnVal
        // }, '金额为')
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})